package process;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ExceptionPerso.ExistingFileException;
import beans.ClientInfo;
import beans.FileMeta;
import common.ConfigurationAppli;
import common.Resultat;
import dao_manager.FileMetaManager;
import dao_manager.FileMetaManagerImpl;
import form.FileUploadForm;

public class ProcessFileUpload extends Action {
    private static final String PARAM_PATH_UPLOAD = "uploadPath";
    private static final String ATT_CLIENT_INFO_ID = "Client_info_id";
    private static final String ATT_USER_NAME    = "userName";
    private static final String ATT_CLIENT         = "client";
    
    @SuppressWarnings( "deprecation" )
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        Logger l = LoggerFactory.getLogger( ProcessFileUpload.class );
        Resultat r=Resultat.SUCCESS;
        ActionErrors erreurs = new ActionErrors();
        
        FileUploadForm fileUploadForm = (FileUploadForm)form;
        FormFile file = fileUploadForm.getFile();
        
        // TODO : configuration
        String filePath = ConfigurationAppli.getInstance().getValue( PARAM_PATH_UPLOAD );
        String NomFiliale = ( (ClientInfo)request.getSession().getAttribute( ATT_CLIENT ) ).getNomFiliale();
        String NomCorrespondant = ( (ClientInfo)request.getSession().getAttribute( ATT_CLIENT ) ).getNomCorrespondant();
        filePath = filePath + "\\"+NomFiliale+"\\"+NomCorrespondant;
        
        File folder = new File(filePath);
        if(!folder.exists())
            folder.mkdirs();
        
        String fileName = file.getFileName();
        
        try
        {
            // Saving file  ------------------------------------------------------------------------------------------------------------
            //--------------------------------------------------------------------------------------------------------------------------
            if ( !( "" ).equals( fileName ) ) {

                File newFile = new File( filePath, fileName );
                l.debug( "Saving in folder  " + filePath +  " the file  "  + newFile.getAbsolutePath());
                
                if ( newFile.exists() ) 
                    throw new ExistingFileException();
                    
                    FileOutputStream fos = new FileOutputStream( newFile );
                    fos.write( file.getFileData() );
                    fos.flush();
                    fos.close();
                
                
                // Persisiting fileMetaData ------------------------------------------------------------------------------------------------
                //--------------------------------------------------------------------------------------------------------------------------
                long Client_ID= (long)request.getSession().getAttribute( ATT_CLIENT_INFO_ID );
                String userName = (String) request.getSession().getAttribute( ATT_USER_NAME );
                String fileDesc = fileUploadForm.getFileDesc();
                FileMeta fileMeta = new FileMeta(Client_ID, userName,  fileDesc, newFile.getAbsolutePath() ) ;
                FileMetaManager fileMetaManager = new FileMetaManagerImpl();
                fileMetaManager.saveFileMeta( fileMeta );
                
            }
        } 
        catch(ExistingFileException e)
        {
            erreurs.add( "dupplicatedFile", new ActionMessage( "errors.dupplicatedFile" ) );
        } catch ( FileNotFoundException e )
        {
            // TODO add exceptions page
            r = Resultat.ECHEC;
        } catch ( IOException e )
        {
            // TODO add exceptions
            r = Resultat.ECHEC;
        }
        catch ( org.hibernate.exception.DataException e)
        {
            erreurs.add( "DescFile", new ActionMessage( "errors.DescFileLong" ) );
        }
        
        if ( !erreurs.isEmpty() )
        {
            saveErrors( request, erreurs );
            return ( new ActionForward( mapping.getInput() ) );
        }
        else
        {
            return mapping.findForward( r.toString().toLowerCase() );
        }
    }

}
